package com.atm.utill;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MailUtils {
    public static void sendEmail(String email, String subject, String content){
        //读取配置文件
        InputStream resourceAsStream = MailUtils.class.getClassLoader().getResourceAsStream("mail.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 邮件发送者和收件人的电子邮件地址
        String senderEmail =properties.getProperty("senderEmail");
        String senderPassword = properties.getProperty("senderPassword");
        // 创建身份验证对象
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        };

        // 创建会话
        Session session = Session.getDefaultInstance(properties, authenticator);
        try {
            // 创建邮件消息
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            message.setSubject(subject);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功！");
        } catch (MessagingException e) {
            System.out.println("邮件发送失败：" + e.getMessage());
        }
    }
}
